/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aexbanner;

import fontys.observer.BasicPublisher;
import fontys.observer.RemotePropertyListener;
import fontys.observer.RemotePublisher;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author Administrator
 */
public class RemoteEffectenbeurs extends UnicastRemoteObject implements IEffectenbeurs {

    private MockFonds[] fondsen;
    private BasicPublisher publisher;
    private Timer timer;
    private double multiplier = 1;
    
    public RemoteEffectenbeurs ()throws RemoteException
    {
        fondsen = new MockFonds[5];
        fondsen[0] = new MockFonds("Philips",100);
        fondsen[1] = new MockFonds("ASML",140);
        fondsen[2] = new MockFonds("Koekjes",60);
        fondsen[3] = new MockFonds("KPN",500.43);
        fondsen[4] = new MockFonds("Tom Tom",4607);
        timer = new Timer();
        timer.schedule(new RemoteEffectenbeurs.MockTimerTask(this), 700, 700);
        publisher = new BasicPublisher(new String[]{"fondsen"});
    }
    
    @Override
    public IFonds[] getKoersen() throws RemoteException{
        return fondsen;
    }
    
    public void randomizeKoersen()throws RemoteException{
        Random r = new Random();
        for(MockFonds fonds : fondsen){
          
            fonds.setKoers(fonds.getKoers()+ (r.nextDouble()*4 - 2 - multiplier));
            if (fonds.getKoers()<=0)
                fonds.setKoers(0);
            
        }
        if (r.nextInt(100)>80)
        {
            multiplier = r.nextDouble()*2 - 1;
        }
        publisher.inform(this,"fondsen", null, fondsen);
    }

    @Override
    public void addListener(RemotePropertyListener rl, String string) throws RemoteException {
        publisher.addListener(rl, string);
    }

    @Override
    public void removeListener(RemotePropertyListener rl, String string) throws RemoteException {
        publisher.removeListener(rl, string);
    }

    
    class MockTimerTask extends TimerTask
    {

        private RemoteEffectenbeurs beurs;
        
        public MockTimerTask(RemoteEffectenbeurs beurs){
            this.beurs = beurs;
        }
        
        @Override
        public void run(){
           try{ beurs.randomizeKoersen();}
           catch(Exception e){}
        }
        
    }
    
}
